import OperationCol from '@/components/OperationCol'
import SealStatus, { statusList } from '@/components/SealStatus'
import {
  adminTypes,
  formatStatus,
  orgLicenseTypes,
  orgTypes,
  useTypes,
  userLicenseTypes,
  sealTypes,
} from '@/lib/sealFormat'
import { desensitization } from '@/lib/utils'
import { RootState } from '@/store'
import { Component, Vue } from 'vue-property-decorator'
import { Action, Mutation, State } from 'vuex-class'
import { UserState } from '@/store/modules/user'
import styles from '../NewApply/NewApply.less'
import { getTimeline } from '@/lib/sealFormat'
// import UpdateSeal from "./UpdateSeal";
import LossSeal from '../LossApply/LossSeal'
import { Table } from 'element-ui'
import TableEmpty from '@/components/tableEmpty'

@Component({})
export default class ReissueApply extends Vue {
  @State((state: RootState) => state.reissueApply.sealList)
  private sealList!: any[]
  @State((state: RootState) => state.reissueApply.total)
  private total!: number
  @State((state: RootState) => state.reissueApply.reissueVisible)
  private reissueVisible!: boolean
  @State((state: RootState) => state.reissueApply.detailVisible)
  private detailVisible!: boolean
  @State((state: RootState) => state.reissueApply.isEdit)
  private isEdit!: boolean
  @State((state: RootState) => state.reissueApply.loading)
  private loading!: boolean
  @State((state: RootState) => state.reissueApply.applyData)
  private applyData!: any
  @State((state: RootState) => state.user)
  private user!: UserState
  @State((state: RootState) => state.reissueApply.saveLoading)
  private saveLoading!: boolean
  @State((state: RootState) => state.reissueApply.title)
  private reissueTitle!: boolean

  private sealType: number[] = []
  private status: number[] = []
  private sealName: string = ''
  private pageIndex: number = 1
  private pageSize: number = 10
  private showTimeline: boolean = false
  private sealOption: any[] = []
  private sealApplyId = ''
  private isDetail = false

  @Mutation('reissueApply/setStateData') private setStateData!: (
    data: any
  ) => {}
  @Action('reissueApply/getList') private getList!: any
  @Action('reissueApply/saveSeal') private saveSeal!: any
  @Action('reissueApply/saveAndSubmit') private saveAndSubmit!: any
  @Action('reissueApply/submitSeal') private submitSeal!: any
  @Action('reissueApply/sealDetail') private sealDetail!: any
  @Action('reissueApply/deleteApply') private deleteApply!: any
  @Action('reissueApply/sealRecall') private sealRecall!: any
  @Action('reissueApply/queryAuditOrg') private queryAuditOrg!: any
  @Action('reissueApply/reissueApply') private reissueApply!: any

  protected render() {
    return (
      <div class="p10">
        <div class={{ [styles.query]: true, custom: true }}>
          <span class={styles.part}>
            <span>印章类别</span>
            <el-select
              v-model={this.sealType}
              multiple
              collapse-tags
              placeholder="默认全部"
            >
              {sealTypes.map((sealType: any, index: number) => (
                <el-option
                  key={sealType.id}
                  label={sealType.value}
                  value={sealType.id}
                />
              ))}
            </el-select>
          </span>
          <span class={styles.part}>
            <span>申请状态</span>
            <el-select
              v-model={this.status}
              multiple
              collapse-tags
              placeholder="默认全部"
            >
              {this.statusArry.map((sealType: any, index: number) => (
                <el-option
                  key={sealType.key}
                  label={sealType.text}
                  value={sealType.key}
                />
              ))}
            </el-select>
          </span>
          <span class={styles.part}>
            <span>申请编号</span>
            <el-input v-model={this.sealApplyId} />
          </span>
          <span class={styles.part}>
            <span>印章名称</span>
            <el-input v-model={this.sealName} />
          </span>
          <span class={styles.part}>
            <el-button
              onClick={this.query}
              loading={this.loading}
              plain
              class="min color-blue"
            >
              搜索
            </el-button>
            <el-button onClick={this.reset} plain class="min color-gray">
              重置
            </el-button>
          </span>
        </div>
        <el-table
          data={this.sealList}
          style="width: 100%"
          v-loading={this.loading}
          ref="table"
        >
          <TableEmpty
            v-show={!this.loading}
            slot="empty"
            msg="暂无匹配的印章补发记录，您可前往申请印章列表或管理印章列表补发印章"
            url={require('@/assets/seal-empty.svg')}
          >
            <el-button onClick={this.toAppliedForMe}>
              前往管理印章列表
            </el-button>
            <el-button type="primary" onClick={this.toNewApply}>
              前往申请印章列表
            </el-button>
          </TableEmpty>
          <el-table-column
            prop="sealApplyRecordId"
            label="申请编号"
            min-width="170"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealName"
            label="印章名称"
            min-width="170"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealType"
            label="印章类别"
            min-width="80"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return formatStatus(sealTypes, scope.row.sealType)
                },
              },
            }}
          />
          <el-table-column
            prop="organizeName"
            label="用章机构名称"
            min-width="170"
            show-overflow-tooltip
          />
          <el-table-column
            prop="createTime"
            label="创建时间"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealApplyStatus"
            label="状态"
            min-width="120"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return <SealStatus status={scope.row.sealApplyStatus} />
                },
              },
            }}
          />

          <el-table-column
            prop="id"
            label="操作"
            width="210"
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <OperationCol
                      operations={this.filterOpera(scope.row.sealApplyStatus)}
                      showNum={4}
                      row={scope.row}
                      index={scope.$index}
                    />
                  )
                },
              },
            }}
          />
        </el-table>
        {this.sealList && this.sealList.length > 0 && (
          <el-pagination
            class={{ [styles.pagination]: true }}
            onSize-change={this.handleSizeChange}
            onCurrent-change={this.handleCurrentChange}
            current-page={this.pageIndex}
            page-sizes={[10, 20, 30]}
            page-size={this.pageSize}
            layout="total, sizes, prev, pager, next, jumper"
            total={this.total}
            pager-count={5}
          />
        )}

        <LossSeal
          onVisibleChange={(val: boolean) => {
            this.setStateData({ reissueVisible: val })
          }}
          title={this.reissueTitle}
          isEdit={this.isEdit}
          isLoss
          data={this.applyData}
          showSubmit={this.isEdit}
          saveLoading={this.saveLoading}
          onSave={this.save}
          visible={this.reissueVisible}
          content="补发"
          sealOption={this.sealOption}
        />
      </div>
    )
  }

  private mounted() {
    const applyId = this.$route.query.id as string
    this.sealApplyId = this.$route.query.recordId as string
    this.query()
    if (applyId) {
      this.gotoReissueDetail(parseInt(applyId), false)
      this.$router.replace({ name: 'reissueApply' })
    }
  }

  get statusArry() {
    return statusList.filter(
      (item: any) =>
        item.key !== 6 &&
        item.key !== 9 &&
        item.key !== 10 &&
        item.key !== 3 &&
        item.key !== 7 &&
        item.key !== 1 &&
        item.key !== 4 &&
        item.key !== 8 &&
        item.key !== 26 &&
        item.key !== 27 &&
        item.key !== 28 &&
        item.key !== 29 &&
        item.key !== 93
    )
  }

  get agentInfo() {
    return {
      agentName: this.user.accountName,
      agentId: this.user.accountUUID,
      agentMobile: this.user.accountMobile,
      agentLicenseType: this.user.accountLicenseType,
      agentLicenseNumber: this.user.accountLicenseNumber,
      organizeName: this.user.organizeName,
      organizeUUID: this.user.organizeUUID,
      organizeType: this.user.organizeType,
      organizeAdministrationLevel: this.user.organizeAdministrationLevel,
      organizeLicenseType: this.user.organizeLicenseType,
      organizeLicenseNumber: this.user.organizeLicenseNumber,
      agentLicenseNumberDes: desensitization(
        this.user.accountLicenseNumber || ''
      ),
      agentMobileDes: desensitization(this.user.accountMobile || ''),
      sealName: this.user.organizeName,
    }
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 0,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.gotoReissueDetail(rows.sealApplyId, true)
        },
      },
      {
        id: 1,
        text: '删除',
        isDelete: true,
        onClick: (index: number, rows: any) => {
          this.delete(rows)
        },
      },
      {
        id: 2,
        text: '修改',
        onClick: (index: number, rows: any) => {
          this.gotoReissueDetail(rows.sealApplyId, false)
        },
      },
      {
        id: 3,
        text: '提交',
        isDelete: true,
        customWarning: '是否确认提交补发申请？',
        onClick: (index: number, rows: any) => {
          this.submit(rows)
        },
      },
      {
        id: 4,
        text: '撤回',
        isDelete: true,
        customWarning: '撤回当前申请后无法恢复，是否继续？',
        onClick: (index: number, rows: any) => {
          this.resetApply(rows)
        },
      },
    ]

    return btns
  }

  private gotoReissueDetail(sealApplyId: any, isDetail: boolean = true) {
    this.sealDetail(sealApplyId).then((data: any) => {
      if (
        !isDetail &&
        (data.sealApplyStatus === 1 ||
          data.sealApplyStatus === 90 ||
          data.sealApplyStatus === 91 ||
          data.sealApplyStatus === 92)
      ) {
        this.isDetail = false
        this.$router.push({
          name: 'applyPage',
          params: { type: 'reissueApply' },
          query: { id: sealApplyId },
        })
        // this.update(data);
      } else {
        this.isDetail = true
        this.detail(data)
      }
    })
  }

  private filterOpera(status: number) {
    return status === 1
      ? this.getOperations.filter((item: any) => item.id !== 4)
      : status === 90 || status === 91 || status === 92
      ? this.getOperations.filter((item: any) => item.id !== 1)
      : status === 2 || status === 3
      ? [this.getOperations[0], this.getOperations[4]]
      : [this.getOperations[0]]
  }

  toNewApply() {
    this.$router.push({ name: 'newApply' })
  }

  toAppliedForMe() {
    this.$router.push({ name: 'myManagingSeal' })
  }

  private query() {
    this.pageIndex = 1
    this.queryList()
  }
  private async queryList() {
    await this.getList(this)
    const table = this.$refs.table as Table
    table.doLayout()
  }

  private update(data: any) {
    this.setStateData({
      reissueVisible: true,
      isEdit: true,
      title: '修改补发申请',
      applyData: Object.assign({}, data, {
        agentName: data.agentName,
        agentLicenseType: data.agentLicenseType,
        agentLicenseTypeName: formatStatus(
          userLicenseTypes,
          data.agentLicenseType
        ),
        agentMobile: data.agentMobile,
        agentLicenseNumber: data.agentLicenseNumber,
        agentLicenseNumberDes: desensitization(data.agentLicenseNumber || ''),
        agentMobileDes: desensitization(data.agentMobile || ''),
        reasonContent: data.applyReason,
        fileKey: data.sealApplyFileKey,
        url: data.sealApplyFileUrl,
        sealSn: data.sealSn,
        sealApplyId: data.sealApplyId,
        sealName: data.sealName,
        startTime: data.sealStartTime,
        endTime: data.sealEndTime,
        organizeName: data.applyOrganizeName,
        organizeCardType: formatStatus(
          orgLicenseTypes,
          data.applyOrganizeLicenseType
        ),
        organizeType: formatStatus(orgTypes, data.applyOrganizeType),
        organizeCardId: data.applyOrganizeLicenseNumber,
        organizeLevel: formatStatus(adminTypes, data.applyOrganizeLevel),
        sealType: formatStatus(sealTypes, data.sealType),
        sealUseType: formatStatus(useTypes, data.sealUseType),
      }),
    })
    this.sealOption = getTimeline(data.sealApplyStatus, this.applyData)
    this.showTimeline = this.sealOption.length > 0
  }

  private delete(row: any) {
    this.deleteApply(row.sealApplyId).then(() => {
      this.$message.success('删除成功')
      this.query()
    })
  }

  private detail(data: any) {
    this.setStateData({
      reissueVisible: true,
      isEdit: false,
      title: '补发申请详情',
      applyData: Object.assign({}, data, {
        agentName: data.agentName,
        agentLicenseType: data.agentLicenseType,
        agentLicenseTypeName: formatStatus(
          userLicenseTypes,
          data.agentLicenseType
        ),
        agentMobile: data.agentMobile,
        agentLicenseNumber: data.agentLicenseNumber,
        agentLicenseNumberDes: desensitization(data.agentLicenseNumber || ''),
        agentMobileDes: desensitization(data.agentMobile || ''),
        reasonContent: data.applyReason,
        fileKey: data.sealApplyFileKey,
        url: data.sealApplyFileUrl,
        sealSn: data.sealSn,
        sealApplyId: data.sealApplyId,
        sealName: data.sealName,
        startTime: data.sealStartTime,
        endTime: data.sealEndTime,
        organizeName: data.applyOrganizeName,
        organizeCardType: formatStatus(
          orgLicenseTypes,
          data.applyOrganizeLicenseType
        ),
        organizeType: formatStatus(orgTypes, data.applyOrganizeType),
        organizeCardId: data.applyOrganizeLicenseNumber,
        organizeLevel: formatStatus(adminTypes, data.applyOrganizeLevel),
        sealType: formatStatus(sealTypes, data.sealType),
        sealUseType: formatStatus(useTypes, data.sealUseType),
      }),
    })
    this.sealOption = getTimeline(data.sealApplyStatus, this.applyData)
    this.showTimeline = this.sealOption.length > 0
  }

  private createForm(sealData: any) {
    sessionStorage.setItem(
      'sealInfo',
      JSON.stringify({
        organize: sealData.organizeName,
        orgType: formatStatus(orgTypes, sealData.organizeType),
        licenseType: formatStatus(
          orgLicenseTypes,
          sealData.organizeLicenseType
        ),
        licenseNumber: sealData.organizeLicenseNumber,
        agentName: sealData.agentName,
        agentLicenseType: formatStatus(
          userLicenseTypes,
          sealData.agentLicenseType
        ),
        agentLicenseNumber: sealData.agentLicenseNumber,
        agentMobile: sealData.agentMobile,
        sealName: sealData.sealName,
        useType: formatStatus(useTypes, sealData.useType),
        auditOrg: sealData.auditOrganizeName,
      })
    )
    window.open(`${window.location.origin}/#/applyForm`, '_blank')
  }

  private submit(row: any) {
    this.submitSeal(row.sealApplyId).then((res: any) => {
      this.query()
    })
  }

  private handleSizeChange(val: number) {
    this.pageIndex = 1
    this.pageSize = val
    this.queryList()
  }

  private handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  private reset() {
    this.sealType = []
    this.status = []
    this.sealName = ''
    this.sealApplyId = ''
    this.query()
  }

  private async save(data: any) {
    this.setStateData({ saveLoading: true })
    this.reissueApply({
      sealApplyId: data.seal.sealApplyId,
      sealSn: data.seal.sealSn,
      applyReason: data.seal.reason,
    })
      .then((res: any) => {
        this.$message.success('提交成功')
        this.setStateData({ saveLoading: false, reissueVisible: false })
        this.query()
      })
      .catch((e: any) => {
        this.setStateData({ saveLoading: false })
      })
  }

  private createApplyForm(sealData: any) {
    sessionStorage.setItem(
      'updateInfo',
      JSON.stringify({
        organize: sealData.organizeName,
        orgType: formatStatus(orgTypes, sealData.organizeType),
        licenseType: formatStatus(orgLicenseTypes, sealData.organizeCardType),
        licenseNumber: sealData.organizeCardId,
        agentName: sealData.agentName,
        agentLicenseType: formatStatus(
          userLicenseTypes,
          sealData.agentLicenseType
        ),
        agentLicenseNumber: sealData.agentLicenseNumber,
        agentMobile: sealData.agentMobile,
        sealName: sealData.sealName,
        newSealName: sealData.newSealName,
        useType: formatStatus(useTypes, sealData.sealUseType),
        sealType: formatStatus(sealTypes, sealData.sealType),
        auditOrg: sealData.auditOrganizeName,
        sealImg: sealData.sealPicUrl,
      })
    )
    window.open(`${window.location.origin}/#/updateForm`, '_blank')
  }

  private resetApply(row: any) {
    this.sealRecall(row.sealApplyId).then((res: any) => {
      this.query()
    })
  }
}
